package cn.sdormitory.controller.academic;


import cn.sdormitory.academic.entity.ClsPracticeInfo;
import cn.sdormitory.academic.entity.ClsPracticeResult;
import cn.sdormitory.academic.service.ClsPracticeResultService;
import cn.sdormitory.common.api.CommonResult;
import cn.sdormitory.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.List;

@RestController
@RequestMapping("/academic/cls/practice/result")
public class ClsPracticeResultController {

    @Autowired
    ClsPracticeResultService clsPracticeResultService;

    @GetMapping("/findListByClsPracticeByInfoId/{infoId}")
    public CommonResult findListByClsPracticeByInfoId(@PathVariable("infoId")Long infoId){
        List<ClsPracticeResult> clsPracticeResults= clsPracticeResultService.findListByClsPracticeByInfoId(infoId);
        return CommonResult.success(clsPracticeResults);
    }

    @PostMapping("/enterClsPracticeResult")
    public CommonResult enterClsPracticeResult(@RequestBody List<ClsPracticeResult> clsPracticeResults){
        //通过人数
        int passNum = 0;
        //未通过人数
        int notPassNum = 0;
        for(ClsPracticeResult clsPracticeResult : clsPracticeResults){
            if(clsPracticeResult.getIsPass() == null){
                return CommonResult.failed("表单未填写完整，请填写完整后提交!");
            }
            //未通过和未勾选是否通过都视为不通过
            if(Integer.valueOf(clsPracticeResult.getIsPass()) == 0
                    || StringUtils.isEmpty(clsPracticeResult.getIsPass())){
                notPassNum ++;
            }else if(Integer.valueOf(clsPracticeResult.getIsPass()) == 1){
                passNum ++;
            }
        }
        if((passNum + notPassNum) != clsPracticeResults.size()){
            return CommonResult.failed("表单未填写完整，请填写完整后提交!");
        }
        ClsPracticeInfo clsPracticeInfo = new ClsPracticeInfo();

        clsPracticeInfo.setPass(passNum);
        clsPracticeInfo.setNotPass(notPassNum);

        if(passNum == clsPracticeResults.size()){
            clsPracticeInfo.setPassRate("100%");
        }else if(passNum == 0) {
            clsPracticeInfo.setPassRate("0%");
        }else {
            double fPassRate = passNum / (double)clsPracticeResults.size();
            DecimalFormat df = new DecimalFormat("0.00");
            String passRate = df.format(fPassRate);
            clsPracticeInfo.setPassRate(passRate.substring(2) + "%");
        }

        clsPracticeResultService.enterClsPracticeResult(clsPracticeResults,clsPracticeInfo);
        return CommonResult.success();
    }

}
